<script lang="ts" setup>
import type { CreateOrUpdateTableRequestData, TableData } from "@@/apis/tables/type"
import type { FormInstance, FormRules } from "element-plus"

import { creategoods, deleteTableDataApi, goodslist, updateTableDataApi } from "@@/apis/goods"
import { shopselect_options } from "@@/apis/common"


const shopList = ref([])
shopselect_options().then(({ data }) => {
  shopList.value = data
})



import { usePagination } from "@@/composables/usePagination"
import { CirclePlus, Delete, Download, Refresh, RefreshRight, Search } from "@element-plus/icons-vue"
import { cloneDeep } from "lodash-es"

defineOptions({
  // 命名当前组件
  name: "ElementPlus"
})


const countries = [
  {
    "id": 10,
    "country_name": "澳大利亚",
    "currency_name": "AUD",
    "currency_symbol": "A$"
  },
  {
    "id": 9,
    "country_name": "俄罗斯",
    "currency_name": "RUB",
    "currency_symbol": "₽"
  },
  {
    "id": 8,
    "country_name": "日本",
    "currency_name": "JPY",
    "currency_symbol": "¥"
  },
  {
    "id": 7,
    "country_name": "英国",
    "currency_name": "GBP",
    "currency_symbol": "£"
  },
  {
    "id": 6,
    "country_name": "印尼",
    "currency_name": "IDR",
    "currency_symbol": "Rp"
  },
  {
    "id": 5,
    "country_name": "墨西哥",
    "currency_name": "MXN",
    "currency_symbol": "$"
  },
  {
    "id": 4,
    "country_name": "巴西",
    "currency_name": "BRL",
    "currency_symbol": "R$"
  },
  {
    "id": 3,
    "country_name": "欧盟",
    "currency_name": "EUR",
    "currency_symbol": "€"
  },
  {
    "id": 2,
    "country_name": "美国",
    "currency_name": "USD",
    "currency_symbol": "$"
  },
  {
    "id": 1,
    "country_name": "中国台湾",
    "currency_name": "TWD",
    "currency_symbol": "NT$"
  }
];
const languages = [
  {
    "id": 9,
    "language": "繁体中文-台湾"
  },
  {
    "id": 10,
    "language": "英语-美国"
  },
  {
    "id": 12,
    "language": "英语-英国"
  },
  {
    "id": 13,
    "language": "德语-欧盟"
  },
  {
    "id": 14,
    "language": "日语-日本"
  },
  {
    "id": 15,
    "language": "法语-欧盟"
  },
  {
    "id": 17,
    "language": "葡萄牙语-巴西"
  },
  {
    "id": 18,
    "language": "西班牙语-欧盟"
  },
  {
    "id": 19,
    "language": "葡萄牙语-欧盟"
  },
  {
    "id": 21,
    "language": "英语-欧盟"
  },
  {
    "id": 23,
    "language": "意大利语-欧盟"
  },
  {
    "id": 24,
    "language": "希腊语-欧盟"
  },
  {
    "id": 26,
    "language": "印尼语-印尼"
  },
  {
    "id": 27,
    "language": "英语-墨西哥"
  },
  {
    "id": 28,
    "language": "俄语-俄罗斯"
  },
  {
    "id": 29,
    "language": "英语-澳大利亚"
  }
];




const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

// #region 增
const DEFAULT_FORM_DATA: CreateOrUpdateTableRequestData = {
  id: undefined,
  username: "",
  password: ""
}
const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
const formData = ref<CreateOrUpdateTableRequestData>(cloneDeep(DEFAULT_FORM_DATA))
const formRules: FormRules<CreateOrUpdateTableRequestData> = {
  // username: [{ required: true, trigger: "blur", message: "请输入用户名" }],
  // password: [{ required: true, trigger: "blur", message: "请输入密码" }]
}
function handleCreateOrUpdate() {
  formRef.value?.validate((valid) => {
    if (!valid) {
      ElMessage.error("表单校验不通过")
      return
    }
    loading.value = true
    const api = formData.value.id === undefined ? creategoods : updateTableDataApi
    api(formData.value).then(() => {
      ElMessage.success("操作成功")
      dialogVisible.value = false
      getTableData()
    }).finally(() => {
      loading.value = false
    })
  })
}
function resetForm() {
  formRef.value?.clearValidate()
  formData.value = cloneDeep(DEFAULT_FORM_DATA)
}
// #endregion

// #region 删
function handleDelete(row: TableData) {
  ElMessageBox.confirm(`正在删除用户：${row.username}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteTableDataApi(row.id).then(() => {
      ElMessage.success("删除成功")
      getTableData()
    })
  })
}
// #endregion

// #region 改
function handleUpdate(row: TableData) {
  dialogVisible.value = true
  formData.value = cloneDeep(row)
}
// #endregion

// #region 查
const tableData = ref<TableData[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  agent_id: '',
  goods_title: '',
  country_id: '',
  language_id: '',
  is_global: '',
  shop_id: '',
})
function getTableData() {
  loading.value = true
  goodslist({
    currentPage: paginationData.currentPage,
    size: paginationData.pageSize,
    agent_id: searchData.agent_id,
    goods_title: searchData.goods_title,
    country_id: searchData.country_id,
    language_id: searchData.language_id,
    is_global: searchData.is_global,
    shop_id: searchData.shop_id,
  }).then(({ data }) => {
    paginationData.total = data.total
    tableData.value = data.data
  }).catch(() => {
    tableData.value = []
  }).finally(() => {
    loading.value = false
  })
}
function handleSearch() {
  paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
}
function resetSearch() {

  Object.assign(searchData, {
    agent_id: '',
    goods_title: '',
    country_id: '',
    language_id: '',
    is_global: '',
    shop_id: '',
  })
  searchFormRef.value?.resetFields()
  handleSearch()
}
// #endregion

// 监听分页参数的变化
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="goods_title" label="商品标题">
          <el-input v-model="searchData.goods_title" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="shop_id" label="店铺id">
          <el-input v-model="searchData.shop_id" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="country_id" label="国家">
          <el-select v-model="searchData.country_id" placeholder="" style="width: 200px;">
            <el-option v-for="item in countries" :key="item.id" :label="item.country_name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="language_id" label="语言">
          <el-select v-model="searchData.language_id" placeholder="" style="width: 200px;">
            <el-option v-for="item in languages" :key="item.language" :label="item.language" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">
            查询
          </el-button>
          <el-button :icon="Refresh" @click="resetSearch">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-button type="primary" :icon="CirclePlus" @click="dialogVisible = true">
            新增商品
          </el-button>
          <!-- <el-button type="danger" :icon="Delete">
            批量删除
          </el-button> -->
        </div>
        <div>
          <!-- <el-tooltip content="下载">
            <el-button type="primary" :icon="Download" circle />
          </el-tooltip> -->
          <el-tooltip content="刷新当前页">
            <el-button type="primary" :icon="RefreshRight" circle @click="getTableData" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData"   >
          <!-- <el-table-column type="selection" width="50" align="center" /> -->
          <el-table-column prop="id" label="ID" align="center" />
          <el-table-column prop="goods_title" label="商品标题" align="center" />
          <el-table-column prop="goods_title_zh" label="商品中文标题" align="center" />
          <el-table-column prop="shop.shop_name" label="店铺" align="center" />
          <el-table-column prop="language.language" label="语言" align="center" />
          <el-table-column prop="country.country_name" label="国家" align="center" />
          <el-table-column prop="goods_price" label="商品价格" align="center" />
          <el-table-column prop="goods_img" label="商品图片" align="center">
            <template #default="scope">
              <img :src="scope.row.goods_img" style="width: 50px;height: 50px;" alt="">
            </template>
          </el-table-column>
          <el-table-column prop="state" label="状态" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.state == 1" type="success">正常</el-tag>
              <el-tag v-else type="danger">禁用</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="create_time" label="创建时间" align="center" />
          <el-table-column prop="update_time" label="更新时间" align="center" />
          <el-table-column fixed="right" label="操作" width="150" align="center">
            <template #default="scope">
              <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">
                修改
              </el-button>
              <!-- <el-button type="danger" text bg size="small" @click="handleDelete(scope.row)">
                删除
              </el-button> -->
            </template>
          </el-table-column>


        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination background :layout="paginationData.layout" :page-sizes="paginationData.pageSizes"
          :total="paginationData.total" :page-size="paginationData.pageSize" :current-page="paginationData.currentPage"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>
    <!-- 新增/修改 -->

    <el-dialog v-model="dialogVisible" :title="formData.id === undefined ? '新增商品' : '修改商品'" width="30%"
      @closed="resetForm">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px" label-position="left">

        <el-form-item prop="type" label="店铺">
          <el-select v-model="formData.shop_id" placeholder="">
            <el-option v-for="item in shopList" :key="item.id" :label="item.shop_name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="goods_title" label="商品名称">
          <el-input v-model="formData.goods_title" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="goods_title_zh" label="商品中文名称">
          <el-input v-model="formData.goods_title_zh" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="goods_price" label="商品价格">
          <el-input v-model="formData.goods_price" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="goods_img" label="商品logo">
          <ImageUpload v-model="formData.goods_img" />
        </el-form-item>



        <el-form-item prop="country_id" label="国家">
          <el-select v-model="formData.country_id" placeholder="">
            <el-option v-for="item in countries" :key="item.id" :label="item.country_name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="language_id" label="语言">
          <el-select v-model="formData.language_id" placeholder="">
            <el-option v-for="item in languages" :key="item.id" :label="item.language" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item prop="state" label="状态">
          <el-radio-group v-model="formData.state">
            <el-radio value="1">正常</el-radio>
            <el-radio label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" :loading="loading" @click="handleCreateOrUpdate">
          确认
        </el-button>
      </template>
    </el-dialog>


  </div>
</template>

<style lang="scss" scoped>
.el-alert {
  margin-bottom: 20px;
}

.search-wrapper {
  margin-bottom: 20px;

  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>